//
//  SearchByChooseViewController.m
//  网络FM
//
//  Created by dlios on 15/5/25.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "SearchByChooseViewController.h"

#import <AFNetworking.h>


#import "SearchAnchorDetailModel.h"

#import "ResultForSearchTableViewCell.h"


#import "PlayerViewController.h"

#import <MJRefresh.h>

#import "HistoryModel.h"
#import "HistoryDatabase.h"

#import "SearchBarView.h"

@interface SearchByChooseViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,assign)NSInteger pageChanged;
@end

@implementation SearchByChooseViewController





- (void)dealloc
{
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.array = [NSMutableArray array];
        self.pageChanged = 3;
        
        
    }
    return self;
}


- (void)loadView
{
    [super loadView];
    [self createTableView];
    [self searchView ];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor colorWithRed:210 / 255.0 green:210 / 255.0 blue:210 / 255.0 alpha:1.0f]];
    
    // 自定义导航栏返回按钮
    UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateNormal];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateHighlighted];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];
}

// 导航栏返回按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 上拉刷新 下拉加载
- (void)Refresh
{
    [self.table reloadData];
    [self.table.header endRefreshing];
}
- (void)Load{
    //choiceDetailcell的网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?v=1&q="];
    NSString *s = [NSString stringWithFormat:@"%@%@&rows=15&offset=%ld",str,self.searchBarText,self.pageChanged * 15];
    
    
    s = [s stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        //判断是否是最后一条
        if (array.count == 0) {
            [self.table removeFooter];
            return ;
        }
        for (NSMutableDictionary *dic  in array) {
            SearchAnchorDetailModel *model = [[SearchAnchorDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
            
        }
        
        self.pageChanged += 1;
        [self.table.footer endRefreshing];
        [self.table reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}




#pragma mark - 创建搜索视图

- (void)searchView
{
    _sea = [[SearchBarView alloc]initWithFrame:CGRectMake(20, 20, self.view.frame.size.width - 40, 30)];
    
    [self.view addSubview:_sea];
    self.sea.search.delegate = self;
    [_sea.search becomeFirstResponder];
    [self.sea release];
}



//点击返回开始网络请求
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.searchBarText = self.sea.search.text;
    [self SearchConnetion];
    return  YES;
}




//点击空白处回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.sea.search resignFirstResponder];
}


//将输入框里输入的数据作为关键字开始搜索(网络请求)
- (void)SearchConnetion
{
    //choiceDetailcell的网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?v=1&q="];
    NSString *s = [NSString stringWithFormat:@"%@%@",str,self.searchBarText];
    s = [s stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        for (NSMutableDictionary *dic  in array) {
            SearchAnchorDetailModel *model = [[SearchAnchorDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
        }
        [self.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}






- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height - 70 - 64) style:UITableViewStyleGrouped];
    self.table.dataSource = self;
    self.table.rowHeight = 50;
    self.table.delegate = self;
    
    //上拉刷新下拉加载
    [self.table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(Refresh)];
    [self.table addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(Load)];
    [self.view addSubview:self.table];
    //[self.table setBackgroundColor:[UIColor greenColor]];
    self.table.showsVerticalScrollIndicator = NO;
    self.table.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
    [self.table release];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellidentify = @"cell";
    ResultForSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentify];
    if (!cell) {
        cell = [[ResultForSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentify];
    }
    //[cell setBackgroundColor:[UIColor blackColor]];
    
    SearchAnchorDetailModel *model = [self.array objectAtIndex:indexPath.row];
    cell.title.text =  model.title;
    [cell.title setTintColor:[UIColor purpleColor]];
   
    //cell出来的动画
    if (indexPath.row % 2) {
        
        cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    else{
        
        cell.frame = CGRectMake(320 ,cell.frame.origin.y ,cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
    
}

//点击搜索出来的某条cell,跳转到播放界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:YES];
    PlayerViewController *player = [[PlayerViewController alloc]init];
    SearchAnchorDetailModel *model = [self.array objectAtIndex:indexPath.row];
    player.picURL = model.cover;
    player.urlForPlay = model.url;
    
    HistoryModel *history = [[HistoryModel alloc]init];
    history.titleName = model.title;
    history.imageName = model.cover;
    history.videoUrl = model.url;
    history.people = model.speak;
    [HistoryDatabase insertWithModel:history];
    
    player.picURL = model.absolute_url;
    player.urlForPlay = model.url;
    player.picURL = model.cover;
    player.tit = model.title;
    player.speaker = model.speak;
    
    UIView *controlView = [self.view.window.subviews objectAtIndex:1];
    [controlView setAlpha:0];

    [self.navigationController pushViewController:player animated:YES];
}






@end
